// import Vue from 'vue';
import axios from 'axios';
// import router from '../router';
import { message } from 'ant-design-vue';

const config = {
  baseURL: '/settlement-api',
  timeout: 60 * 1000,
  withCredentials: true,
}

const _axios = axios.create(config);


_axios.interceptors.request.use(
  (_config) => {
    if(_config.url.startsWith('/basic')) {
      _config.baseURL = '';
    }
    _config.headers.token = localStorage.getItem('token');
    return _config;
  },
  (error) => Promise.reject(error),
);

const downloadUrl = ['/booking/export', '/booking/exportStatistics', '/booking/exportDay'];

_axios.interceptors.response.use((response) => {
  const { status, data, config } = response;
  if (status !== 200) {
    message.error(data.msg);
    return;
  }
  // 模拟登陆
  if(config.url.startsWith('/basic')){
    return data
  }
  // 文件下载
  if(downloadUrl.includes(config.url)) {
    if(data.type ===  'application/json') {
      message.error('导出失败');
      return Promise.reject();
    } else if(data.type ===  'application/vnd.ms-excel') {
      return data;
    }
  }
  if(data.code === 200) {
    return data.data;
  } else if(data.code === 401){
    // router.push({ name: 'Login', query: { ReturnUrl: window.location.pathname } });
  } else {
    message.error(data.msg);
    return Promise.reject(data);
  }
},
(error) => {
  const { status } = error.response;
  if (status === 401) {
    // router.push({ name: 'Login', query: { ReturnUrl: window.location.pathname } });
  }
  return Promise.reject(error);
});


_axios.upload = (url, data) => {
  const form = new FormData();
  Object.keys(data).forEach((val) => {
    form.append(val, data[val]);
  });
  return _axios.post(url, form, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

_axios.postFormData = (url, data) => {
  const form = new FormData();
  Object.keys(data).forEach((val) => {
    form.append(val, data[val]);
  });
  return _axios.post(url, form, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

_axios.downLoadFileBlob = (url) => {
  return _axios.get(url, {}, {
    responseType: 'blob'
  });
};

// const installAxios = (Vue) => {
//   if(installAxios.installed) {
//     return;
//   }
//   installAxios.installed = true;
//   window.axios = _axios;
//   Object.defineProperties(Vue.prototype, {
//     axios: {
//       get() {
//         return _axios;
//       }
//     },
//     $axios: {
//       get() {
//         return _axios;
//       }
//     }
//   })
// };

// Vue.use(installAxios);

export default _axios;

